<template>
  <t-card :bordered="false">
    <!-- 容器 -->
    <div class="container">
      <t-space class="left" direction="vertical">
        <!-- 公司 -->
        <t-select
          v-model:value="searchParams.companyId"
          :options="companySimpleList"
          :keys="{ label: 'name', value: 'id' }"
          label="归属公司："
          filterable
          @change="handleChangeCompany"
        />
        
        <!-- 新建模板 -->
        <t-button
          v-permission="['system:collection-model-config:create']"
          block
          @click="
            handleOpenLeftDialog('create', {
              companyId: searchParams.companyId,
            })
          "
        >
          新建模板
        </t-button>
        <!-- 模板树 -->
        <t-tree
          :data="categoryTree"
          activable
          expand-on-click-node
          hover
          :keys="{ label: 'name', value: 'id' }"
          max-height="calc(100vh - 380px)"
          @click="handleClickCategoryTree"
        >
          <template #operations="{ node }">
            <t-space>
              <t-icon
                v-permission="['system:collection-model-config:update']"
                name="edit"
                @click="handleOpenLeftDialog('update', { id: node.data.id })"
              />
              <t-popconfirm
                content="确认要删除该项吗？"
                @confirm="handleDeleteLeft({ id: node.data.id })"
              >
                <t-icon v-permission="['system:collection-model-config:delete']" name="delete" />
              </t-popconfirm>
            </t-space>
          </template>
        </t-tree>
      </t-space>
      <t-divider class="divider" layout="vertical" />
      <div v-show="searchParams.modelId" class="right">
        <!-- 自定义搜索 -->
        <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable">
          <t-col :span="3">
            <t-form-item label="期数" name="payNumber">
              <t-input v-model:value="params.payNumber" clearable placeholder="" />
            </t-form-item>
          </t-col>
          <t-col :span="3">
            <t-form-item label="收款阶段" name="paymentStage">
              <t-input v-model:value="params.paymentStage" clearable placeholder="" />
            </t-form-item>
          </t-col>
        </custom-search>
        <!-- 自定义表格 -->
        <custom-table
          ref="customTableRef"
          row-key="id"
          :columns="columns"
          :api="collectionConfigCRUD.page"
          column-controller-key="CollectionConfigList"
        >
          <template #topContent>
            <div style="margin-bottom: var(--td-comp-margin-xxl)">
              <t-button
                v-permission="['system:collection-config:create']"
                @click="
                  handleOpenDialog('create', {
                    companyId: searchParams.companyId,
                    modelId: searchParams.modelId,
                  })
                "
              >
                新建收款
              </t-button>
            </div>
          </template>
         
          <template #engineeringStage="{ row }">
            <t-cascader
                v-model:value="row.engineeringStage"
                :options="stageTree"
                :keys="{ value: 'id', label: 'stageName' }"
                placeholder=""
                :readonly="true"
                :borderless="true"
                class="text-only-cascader"
              />
          </template>
          <template #operation="{ row }">
            <t-space>
              <t-link
                v-permission="['system:collection-config:query']"
                theme="primary"
                @click="handleOpenDialog('read', { id: row.id })"
              >
                详情
              </t-link>
              <t-link
                v-permission="['system:collection-config:update']"
                theme="primary"
                @click="handleOpenDialog('update', { id: row.id })"
              >
                编辑
              </t-link>
              <t-popconfirm
                content="确认要删除该项吗？"
                @confirm="handleDelete({ id: row.id })"
              >
                <t-link v-permission="['system:collection-config:delete']" theme="danger"> 删除 </t-link>
              </t-popconfirm>
            </t-space>
          </template>
        </custom-table>
      </div>
      <t-empty v-show="!searchParams.modelId" class="right" title="请先选择模板" style="margin-top: 30vh" />
    </div>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="collectionConfigCRUD"
      header="*收款"
      @request-success="handleDialogRequestSuccess"
    >
     
    <t-form-item label="期数" name="payNumber" :rules="[{ required: true, message: '请输入期数' }]">
        <t-input-number
          v-model:value="formData.payNumber"
          placeholder="请输入期数"
          clearable
          :readonly="readonly"
          style="width: 100%"
          :min="1"
        />
      </t-form-item>
      <t-form-item label="收款阶段" name="paymentStage" :rules="[{ required: true, message: '请输入收款阶段' }]">
        <t-input v-model:value="formData.paymentStage" placeholder="请输入收款阶段" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="收款节点" name="engineeringStage" :rules="[{ required: true, message: '请输入收款节点' }]" v-if="formData.payNumber&&formData.payNumber>1">
        <t-cascader
            v-model:value="formData.engineeringStage"
            :options="stageTree"
            :keys="{ value: 'id', label: 'stageName' }"
            placeholder=""
            filterable
            clearable
            :readonly="readonly"
            
          />
      </t-form-item>
      <t-form-item label="收款比例" name="proportion" :rules="[{ required: true, message: '请输入收款比例' }]">
        <t-input-number
          v-model:value="formData.proportion"
          placeholder="请输入收款比例"
          clearable
          :readonly="readonly"
          style="width: 100%"
          :format="numberFormat"
        />
      </t-form-item>
      
    </custom-dialog>
        <!-- 左侧新增材料对话框 -->
    <custom-dialog
      ref="customDialogLeftRef"
      v-slot="{ formData, readonly }"
      :api-map="collectionModelConfigCRUD"
      header="*收款"
      @request-success="handleDialogRequestSuccessLeft"
    >
      <t-form-item label="模板名称" name="name" :rules="[{ required: true, message: '请输入模板名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入模板名称" clearable :readonly="readonly" />
      </t-form-item>
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'LaborCosts',
};
</script>

<script setup lang="ts">
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import { onMounted, reactive, ref, useTemplateRef } from 'vue';

import { collectionConfigCRUD, engineeringConfigCRUD, collectionModelConfigCRUD } from '@/api/config/common-config';

import { getCompanyList } from '@/api/system/dept';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import { useDictionaryStore } from '@/store';
import listToTree from '@/utils/listToTree';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 搜索参数
const searchParams = reactive({
  companyId: null,
  modelId: null
});
// 公司精简列表
const companySimpleList = ref([]);
// 处理获取公司精简列表
const handleGetCompanySimpleList = async () => {
  return getCompanyList().then((data) => {
    companySimpleList.value = data;
    searchParams.companyId = data[0].id;
  });
};
// 模板列表
const categoryList = ref([]);
// 模板树
const categoryTree = ref([]);
// 处理获取模板
const handleGetCategory = () => {
  const params = {
    companyId: searchParams.companyId,
    pageSize: -1,
  };
  collectionModelConfigCRUD.page(params).then((data) => {
    categoryList.value = data.list;
    categoryTree.value = listToTree(data.list);
  });
};
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');

// columns
const columns: TableCol[] = [
  { colKey: 'payNumber', title: '期数', width: 60 },
  { colKey: 'paymentStage', title: '收款阶段', width: 100 },
  { colKey: 'engineeringStage', title: '收款节点', width: 250 },
  { colKey: 'proportion', title: '收款比例(%)', width: 180 },
  { colKey: 'operation', title: '操作', width: 160, fixed: 'right' },
];
// 精简节点树
const stageTree = ref([]);
// 处理获取精简节点
const handleGetSimpleStageTree = () => {
  const params = {
    pageSize:-1
  }
  engineeringConfigCRUD.page(params).then((data) => {
    stageTree.value = listToTree(data.list);
  });
};

const numberFormat = (value:any) => `${value} %`;
// 处理初始化表格
const handleInitTable = () => {
  const params = {
    ...customSearchRef.value.params,
    companyId: searchParams.companyId,
    modelId: searchParams.modelId,
  };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(async () => {
  await handleGetSimpleStageTree();
  await handleGetCompanySimpleList();
  handleGetCategory();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.params.isCategory === 1) {
    handleGetCategory();
  } else {
    if (result.mode === 'create') handleInitTable();
    if (result.mode === 'update') handleRefreshTable();
  }
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  collectionConfigCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      if (params.isCategory === 1) {
        handleGetCategory();
      } else {
        handleRefreshTable();
      }
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理点击模板树
const handleClickCategoryTree = ({ node }: { node: TreeNodeModel }) => {
  if (!node.data.children) {
    searchParams.modelId = node.value;
    handleInitTable();
  }
};
// 自定义材料左侧对话框ref
const customDialogLeftRef = useTemplateRef('customDialogLeftRef');
// 处理打开对话框
const handleOpenLeftDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogLeftRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccessLeft = (result: Record<string, any>) => {
  handleGetCategory();
};
// 处理删除左侧
const handleDeleteLeft = (params: Record<string, any>) => {
  if(params.children) {
    MessagePlugin.error('有子节点不允许删除');
  } else {
    collectionModelConfigCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功'); 
      handleGetCategory();
      searchParams.modelId = null;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
  }
 
};
// 公司change
const handleChangeCompany = () => {
  searchParams.modelId = null;
  handleGetCategory();
}
</script>

<style lang="less" scoped>
// 容器
.container {
  display: flex;
  justify-content: center;
  align-items: flex-start;

  .left {
    width: 280px;
    height: calc(100vh - 236px);
    overflow: hidden;

    :deep(.t-tree) {
      padding-right: 8px;

      &::-webkit-scrollbar {
        width: 8px;
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        border: 2px solid transparent;
        background-clip: content-box;
        background-color: var(--td-scrollbar-color);
      }
    }
  }

  .divider {
    height: calc(100vh - 236px);
  }

  .right {
    // width: calc(100% - 325px);
    flex:1;
  }
}
</style>
